package com.orange.core.security.filter;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.orange.core.security.token.WxAuthenticationToken;
import com.orange.core.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@Slf4j
public class WxAuthenticationFilter extends AbstractAuthenticationFilter {

    private final ObjectMapper objectMapper;

    public WxAuthenticationFilter(ObjectMapper objectMapper, AuthenticationSuccessHandler successHandler, AuthenticationFailureHandler failureHandler) {
        super(Constants.USER_WX_MINI_SIGN_IN_PATH, successHandler, failureHandler);
        this.objectMapper = objectMapper;
    }

    @Override
    protected Authentication obtainToken(HttpServletRequest request) {
        try {
            Authentication token = objectMapper.readValue(request.getInputStream(), WxAuthenticationToken.class);
            if (StrUtil.isBlank(token.getName())) {
                throw new InsufficientAuthenticationException("获取code失败");
            }
            return new WxAuthenticationToken(token.getName().trim());
        } catch (IOException e) {
            log.error("获取code失败", e);
            throw new InsufficientAuthenticationException("获取code失败");
        }
    }
}
